<template>
    <div>
        <div class="container">
            <el-main>
                <el-form ref="advertPicFormRef" :rules="advertPicFormRules" :model="advertPicForm" :label-width="formLabelWidth">
                    <el-form-item label="ID" prop="id" v-if="false">
                        <el-input v-model="advertPicForm.id" />
                    </el-form-item>
                    <el-form-item label="图片类型" prop="advPicType">
                        <el-input v-model="advertPicForm.advPicType" clearable class="handle-input mr10" v-if="false"/>
                        <el-select v-model="advertPicForm.advPicType" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in advTypeOption" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"/>
                        </el-select>
                    </el-form-item>
  					<!-- 资讯常规信息 -->
                    <el-form-item label="广告位图片名称" prop="advPicName">
                        <el-input v-model="advertPicForm.advPicName" clearable class="handle-input mr10" />
                    </el-form-item>
                    <el-form-item label="广告位图片" prop="advPicUrl">
                        <el-input v-model="advertPicForm.advPicUrl" placeholder="封面图片" v-if="false"/>
						<el-avatar v-if="masterImageUrl" class="avatar" shape="square" :src="masterImageUrl" />
                        <VAvatarUpload v-else v-bind:selectValue="VAvatar" @avatar="func_loadVAvatarData" />
                    </el-form-item>
                    <el-form-item label="数据排序" prop="sort">
                        <el-input v-model="advertPicForm.sort" v-if="false"></el-input>
                        <el-input-number v-model="sortNum" :min="1" :max="100" :step="1" />
                    </el-form-item>
                    <el-form-item label="是否显示" prop="isStatus">
                        <el-input v-model="advertPicForm.isStatus" v-if="false"/>
                        <el-switch v-model="advertPicForm.isStatus" 
                            :active-value= "2001" :inactive-value= "2002"
                            inline-prompt active-text="是" inactive-text="否" />
                    </el-form-item>
                   <el-form-item label="是否外部链接" prop="isInner">
                        <el-input v-model="advertPicForm.isInner" v-if="false"/>
                        <el-switch v-model="advertPicForm.isInner" 
                            :active-value= "1" :inactive-value= "0"
                            inline-prompt active-text="是" inactive-text="否" />
                    </el-form-item>
                    <el-form-item label="广告位外部链接" prop="advOuterLink">
                        <el-input v-model="advertPicForm.advOuterLink" clearable class="handle-input mr10" />
                    </el-form-item>
                    <el-form-item label="广告位内部链接" prop="advInnerLink">
                        <el-input v-model="advertPicForm.advInnerLink" clearable class="handle-input mr10" />
                    </el-form-item>
                </el-form>
            </el-main>
			<el-footer>
                <el-button type="primary" @click="func_onSubmit" plain>保存数据</el-button>
                <el-button type="success" @click="func_onReset" plain>重置表单</el-button>
                <el-button @click="func_closeDialog" plain>取 消</el-button>
			</el-footer>
        </div>
    </div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { findAdvertPicInfoById, addAdvertPic, saveAdvertPic } from "../../../../api/hairmanager/advertPic";
import { loadAdvertOpenWayDict, loadAdvertPositionDict, findChildDictionaryListByParentId } from "../../../../api/dict";
import { NO_DATA_SELECT_ERROR, SUCCESS_ADDDATA_DIALOG_MESSAGE, SUCCESS_DELDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE, formLabelWidth, } from "../../../../api/CommonErrorMessage.js";
import VAvatarUpload from '../../../../components/AvatarUpload.vue';

export default {
    name: "advertPicForm",
    components: {VAvatarUpload,},
	props:{
        selectValue: Object,
	},
    emits: ["advertPicData"],
    setup(props, cex){
		onMounted(() => {
		});
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");

		/**
         * @name 定义业务表单
         */
        const getInitFormData = () => {
            return {
                advInnerLink: '',
                advOuterLink: '',
                advPicFile: '',
                advPicName: '',
                advPicType: '',
                advPicUrl: '',
                createTime: '',
                id: 0,
                isInner: 0,
                isStatus: 0,
                sdvSno: '',
                sort: 0,
                strAdvPicType: '',
                strIsStatus: ''
            }
        };
        /**
         * @name 表单初始化
         */
        const resetAdvertPicForm = () => {
            Object.assign(advertPicForm, getInitFormData());
            sortNum.value = 1;
            masterImageUrl.value = '';
        };
		// 新闻资讯表单数据
        const advertPicForm = reactive(getInitFormData());
        const advertPicFormRef = ref(null);
        const advertPicFormRules = {
            masterImageUrl: [
                { required: true, message: "请上传图片", trigger: "blur" },
            ],
            advPicName: [
                { required: true, message: "请输入广告位图片名称", trigger: "blur" },
            ],
        };
        const sortNum = ref(0);
        const loadDataFlg = ref(false);
        const advTypeOption = ref([]);
        // =========================================================================================
        // 提交
        const func_onSubmit = () => {
            advertPicForm['sort'] = sortNum;
            // 表单校验
            advertPicFormRef.value.validate((valid) => {
                if (valid) {
                    if(loadDataFlg.value){
                        saveAdvertPic(advertPicForm).then((res) => {
                            if(res.code != 200) {
                                if(res.type == 0) {
                                    ElMessage.warning(res.message);
                                } else {
                                    ElMessage.error(res.message);
                                }
                            } else {
                                ElMessage.success(SUCCESS_EDITDATA_DIALOG_MESSAGE);
                                cex.emit('advertPicData', {state: 1, data: []});
                            }
                        });
                    } else {
                        addAdvertPic(advertPicForm).then((res) => {
                            if(res.code != 200) {
                                if(res.type == 0) {
                                    ElMessage.warning(res.message);
                                } else {
                                    ElMessage.error(res.message);
                                }
                            } else {
                                ElMessage.success(SUCCESS_ADDDATA_DIALOG_MESSAGE);
                                cex.emit('advertPicData', {state: 1, data: []});
                            }
                        });
                    }
                    resetAdvertPicForm();
                } else {
                    return false;
                }
            });
        };
        // 重置
        const func_onReset = () => {
            resetAdvertPicForm();
        };
        const func_closeDialog = () => {
            cex.emit('advertPicData', {state: 1, data: []});
        };
        const func_onload = () =>{
            let query = {parentId: 71};
            findChildDictionaryListByParentId(query).then((res) => {
                res.data.list.forEach((item) => {
                    let obj = {};
                    if(item['dicCode'] === advertPicForm['advType']){
                        obj = {value : item['dicCode'], label : item['dicName'], disabled: true}
                    } else {
                        obj = {value : item['dicCode'], label : item['dicName'], disabled: false}
                    }
                    advTypeOption.value.unshift(obj);
                });
            });
        }
        func_onload();
		// 主图上传 ========================================================================================= START
        let masterImageUrl = ref('');
        const VAvatar = reactive({});
        const func_loadVAvatarData = (v) => {
            if(v['state'] === 1) {
                masterImageUrl.vlaue = v['imgUrl'];
                advertPicForm['advPicUrl'] = v['imgUrl'];
            }
        };
        // 主图上传 ========================================================================================= END
        // =========================================================================================================
        // 业务数据监听
        watch(() => props.selectValue, (val) => {
			if(val['load']){
                findAdvertPicInfoById(props.selectValue['id']).then((res) => {
                    Object.keys(advertPicForm).forEach((item) => {
                        advertPicForm[item] = res.data[item];
                    });
                    advertPicForm['advPicType'] = val['type']+'';
                    masterImageUrl.value = res.data['advPicUrl'];
                    sortNum.value = res.data['sort'];
                });
			} else {
                resetAdvertPicForm();
                advertPicForm['advPicType'] = val['type']+'';
            }
            loadDataFlg.value = val['load'];
        },{deep: true,immediate: true});
        // =========================================================================================================
        return {
			// 系统变量 =========================================================================================
            formLabelWidth, advertPicForm, advertPicFormRef, advertPicFormRules, sortNum, loadDataFlg, advTypeOption,
			// 主业务调用方法 =========================================================================================
            func_onload, getInitFormData, resetAdvertPicForm, func_onSubmit, func_onReset, func_closeDialog,
			// 图片文件处理 =========================================================================================
            masterImageUrl, VAvatar, func_loadVAvatarData,
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 300px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.avatar {
    width: 100%;
    height: 100%;
    display: block;
    align: center;
}
</style>